package org.paradigmshift.cumulusfracto.filesystem;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.jlan.netbios.server.NetBIOSNameServer;
import org.alfresco.jlan.server.NetworkServer;
import org.alfresco.jlan.server.config.InvalidConfigurationException;
import org.alfresco.jlan.smb.server.CIFSConfigSection;
import org.alfresco.jlan.smb.server.SMBServer;
import org.apache.log4j.Logger;


public class CumulusFractoCifsServer {
	
	private static final Logger log = Logger.getLogger( CumulusFractoCifsServer.class );
	
	private CumulusFractoServerConfiguration serverConfig = new CumulusFractoServerConfiguration();
	private List<NetworkServer> servers = new ArrayList<NetworkServer>();
	
	public CumulusFractoCifsServer() {
		 
		try {
			serverConfig.init();
		}
		catch ( InvalidConfigurationException e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public boolean isStarted() {
		
		return ( !servers.isEmpty() && serverConfig.isServerRunning( "CIFS" ) );
	}
	
	public void start() throws SocketException, IOException {
		
		CIFSConfigSection cifsConfig = (CIFSConfigSection) serverConfig.getConfigSection( CIFSConfigSection.SectionName );
		if ( cifsConfig != null ) {
			
			// Create the NetBIOS name server if NetBIOS SMB is enabled
			if ( cifsConfig.hasNetBIOSSMB() ) servers.add( new NetBIOSNameServer( serverConfig ) );
			
			// Create the SMB server
			servers.add( new SMBServer( serverConfig ) );
			
			// Add the servers to the configuration
			for ( NetworkServer server : servers ) {
				
				serverConfig.addServer( server );
			}
		}
		
		// Start the servers
		for ( NetworkServer server : servers ) {
			
			if ( log.isDebugEnabled() ) log.debug( "Starting server: " + server.getProtocolName() );
			
			server.startServer();
		}
	}
	
	public void stop() {
		
		// TODO Ensure all disks are removed
		
		// Stop the servers
		if ( serverConfig != null ) {
			
			for ( NetworkServer server : servers ) {
				
				server.shutdownServer( false );
			}
			
			servers.clear();
		}
	}
	
	public void addDisk( String name, String comment ) throws InvalidConfigurationException {
		
		serverConfig.addDisk( name, comment );
	}
	
	public void removeDisk( String name ) throws InvalidConfigurationException {
		
		serverConfig.removeDisk( name );
	}
	
	public void removeAllDisks() {
		
		// TODO
	}
}
